package com.dragee.modules.work.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dragee.common.PageUtils;
import com.dragee.config.exception.BusinessException;
import com.dragee.constants.CommonConstants;
import com.dragee.modules.sys.entity.FilesEntity;
import com.dragee.modules.sys.entity.LoginUser;
import com.dragee.modules.work.dao.ApplyDao;
import com.dragee.modules.work.dto.TeamPerson;
import com.dragee.modules.work.entity.*;
import com.dragee.modules.work.service.*;
import com.dragee.utils.LoginUserUtil;
import com.dragee.utils.UploadUtil;
import com.dragee.utils.WrapperUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service("applyService")
public class ApplyServiceImpl extends ServiceImpl<ApplyDao, ApplyEntity> implements ApplyService {


    @Resource
    private ApplyDao applyDao;

    private String business = "apply";

    @Autowired
    private CompetitionService competitionService;
    @Autowired
    private TeamService teamService;
    @Autowired
    private CompetitionProjectService competitionProjectService;
    @Autowired
    private ApplyProjectService applyProjectService;
    @Autowired
    private TeamRefereeService teamRefereeService;
    @Autowired
    private TeamOtherService teamOtherService;
    @Autowired
    private TeamLeaderService teamLeaderService;
    @Autowired
    private TeamCoachService teamCoachService;
    @Autowired
    private TeamAthleteService teamAthleteService;

    @Value("${webull.mapUploadPath}")
    private String rootPath;

    private final String file_join_Pay = "joinPay";
    private final String file_music = "music";
    private final String urlPath = "http://47.101.130.227:9000/api";
    /**
    * 列表
    */
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        int limit = params.get(CommonConstants.LIMIT) == null
                ?CommonConstants.LIMIT_SIZE:Integer.parseInt(params.get(CommonConstants.LIMIT).toString());
        int start = params.get(CommonConstants.START) == null
                ?CommonConstants.START_SIZE:Integer.parseInt(params.get(CommonConstants.START).toString());
        QueryWrapper<ApplyEntity> wrapper =
                WrapperUtil.getWrapper(business, params, ApplyEntity.class);
        LoginUser loginUser = LoginUserUtil.getLoginUser();
        if ("duiwu".equals(loginUser.getType())) {
            TeamEntity team = teamService.getTeamByUserId(loginUser.getUserId().toString());
            if (team != null) {
                wrapper.eq("teamId", team.getId());
            }
        }
        wrapper.eq("isImport", 0);
        IPage<ApplyEntity> page = new Page<>(start, limit);
        page = baseMapper.selectPage(page, wrapper.select());
        for (ApplyEntity record : page.getRecords()) {
            TeamEntity team = teamService.getById(record.getTeamId());
            if (team != null) {
                record.setTeamName(team.getName());
                record.setTeamCode(team.getCode());
            }
        }
        return new PageUtils(page);
    }



    @Override
    public ApplyProjectEntity getApplyProjectInfo (String applyProjectId) {
        ApplyProjectEntity project = applyProjectService.getById(applyProjectId);
        CompetitionProjectEntity competitionProject
                = competitionProjectService.getById(project.getProjectId());
        project.setProjectName(competitionProject.getName());

        FilesEntity files = UploadUtil.getFilesEntity(file_music, project.getId().toString());
        if (files != null) {
            project.setFileMusicUrl(files.getFilePath());
            project.setFileMusicName(files.getFileName());
            project.setFileId(files.getId().toString());
        }
        List<TeamPerson> athletes = new ArrayList<>();
        String[] athleteIds = StrUtil.isNotBlank(project.getAthleteIds()) ? project.getAthleteIds().split(",") : new String[]{};
        for (String athleteId : athleteIds) {
            TeamAthleteEntity teamAthleteEntity = teamAthleteService.getById(athleteId);
            athletes.add(new TeamPerson(teamAthleteEntity));
        }
        project.setAthletes(athletes);
        return project;
    }

    @Override
    public ApplyEntity getApplyInfo(String id) {
        ApplyEntity apply = getById(id);
        if (apply == null) {
            throw new BusinessException("报名数据异常, 当前报名数据不存在");
        }
        TeamEntity team = teamService.getById(apply.getTeamId());
        if (team == null) {
            throw new BusinessException("报名数据异常, 当前报名队伍不存在");
        }
        apply.setTeamName(team.getName());
        apply.setTeamCode(team.getCode());
        apply.setTeamCity(team.getCity());
        apply.setTeamProvince(team.getProvince());
        FilesEntity file = UploadUtil.getFilesEntity(file_join_Pay, id);
        if (file != null) {
            apply.setFilePayUrl(file.getFilePath());
            apply.setFilePayName(file.getFileName());
            apply.setFileId(file.getId().toString());
        }

        String[] coachIds = StrUtil.isNotBlank(apply.getCoachIds())
                ? apply.getCoachIds().split(",") : new String[]{};
        String[] leaderIds = StrUtil.isNotBlank(apply.getLeaderIds())
                ? apply.getLeaderIds().split(",") : new String[]{};
        String[] otherIds = StrUtil.isNotBlank(apply.getOtherIds())
                ? apply.getOtherIds().split(",") : new String[]{};
        String[] refereeIds = StrUtil.isNotBlank(apply.getRefereeIds())
                ? apply.getRefereeIds().split(",") : new String[]{};
        List<TeamPerson> coachs = new ArrayList<>();
        for (String coachId : coachIds) {
            TeamCoachEntity obj = teamCoachService.getById(coachId);
            coachs.add(new TeamPerson(obj));
        }
        apply.setCoachs(coachs);
        List<TeamPerson> leaders = new ArrayList<>();
        for (String leaderId : leaderIds) {
            TeamLeaderEntity obj = teamLeaderService.getById(leaderId);
            leaders.add(new TeamPerson(obj));
        }
        apply.setLeaders(leaders);
        List<TeamPerson> others = new ArrayList<>();
        for (String otherId : otherIds) {
            TeamOtherEntity obj = teamOtherService.getById(otherId);
            others.add(new TeamPerson(obj));
        }
        apply.setOthers(others);
        List<TeamPerson> referees = new ArrayList<>();
        for (String refereeId : refereeIds) {
            TeamRefereeEntity obj = teamRefereeService.getById(refereeId);
            if (obj != null) {
                referees.add(new TeamPerson(obj));
            }
        }
        apply.setReferees(referees);

        List<ApplyProjectEntity> applyProjects = applyProjectService
                .list(new QueryWrapper<ApplyProjectEntity>()
                        .eq("applyId", apply.getId()));
        for (ApplyProjectEntity project : applyProjects) {
            CompetitionProjectEntity competitionProject
                    = competitionProjectService.getById(project.getProjectId());
            project.setProjectName(competitionProject.getName());

            FilesEntity files = UploadUtil.getFilesEntity(file_music, project.getId().toString());
            if (files != null) {
                project.setFileMusicUrl(files.getFilePath());
                project.setFileMusicName(files.getFileName());
                project.setFileId(files.getId().toString());
            }
            List<TeamPerson> athletes = new ArrayList<>();
            String[] athleteIds = StrUtil.isNotBlank(project.getAthleteIds()) ? project.getAthleteIds().split(",") : new String[]{};
            for (String athleteId : athleteIds) {
                TeamAthleteEntity teamAthleteEntity = teamAthleteService.getById(athleteId);
                athletes.add(new TeamPerson(teamAthleteEntity));
            }
            project.setAthletes(athletes);
            List<TeamPerson> projectCoachs = new ArrayList<>();
            String[] projectCoachIds = StrUtil.isNotBlank(project.getProjectCoachIds()) ? project.getProjectCoachIds().split(",") : new String[]{};
            for (String projectCoachId : projectCoachIds) {
                TeamCoachEntity teamCoachEntity = teamCoachService.getById(projectCoachId);
                projectCoachs.add(new TeamPerson(teamCoachEntity));
            }
            project.setProjectCoachs(projectCoachs);

        }
        apply.setProjects(applyProjects);
        return apply;
    }

    @Override
    public String getMusicUrl(String applyProjectId) {
        FilesEntity files = UploadUtil.getFilesEntity(file_music, applyProjectId);
        if (files != null) {
            return urlPath + files.getFilePath();
        }
        return null;
    }

    @Override
    public String getJoinPayUrl(String applyId) {
        FilesEntity files = UploadUtil.getFilesEntity(file_join_Pay, applyId);
        if (files != null) {
            return urlPath + files.getFilePath();
        }
        return null;
    }

    @Override
    public void setApplyProject(ApplyProjectEntity project) {
        CompetitionProjectEntity competitionProject
                = competitionProjectService.getById(project.getProjectId());
        project.setProjectName(competitionProject.getName());
        FilesEntity files = UploadUtil.getFilesEntity(file_music, project.getId().toString());
        if (files != null) {
            project.setFileMusicUrl(files.getFilePath());
            project.setFileMusicName(files.getFileName());
            project.setFileId(files.getId().toString());
        }
        List<TeamPerson> athletes = new ArrayList<>();
        String[] athleteIds = StrUtil.isNotBlank(project.getAthleteIds()) ? project.getAthleteIds().split(",") : new String[]{};
        for (String athleteId : athleteIds) {
            TeamAthleteEntity teamAthleteEntity = teamAthleteService.getById(athleteId);
            athletes.add(new TeamPerson(teamAthleteEntity));
        }
        //设置队伍信息
        ApplyEntity apply = this.getById(project.getApplyId());
        TeamEntity team = teamService.getById(apply.getTeamId());
        project.setTeamName(team.getName());
        project.setAthletes(athletes);
    }

    @Override
    public List<ApplyProjectEntity> getApplyProjectByStatus(String applyProjectIds, String status) {
        String[] apIds = applyProjectIds.split(",");
        QueryWrapper<ApplyProjectEntity> qw = new QueryWrapper<ApplyProjectEntity>()
                .in("id", apIds);
        if (StrUtil.isNotBlank(status)) {
            qw.eq("status", status);
        }
        List<ApplyProjectEntity> aps = applyProjectService.list(qw);
        for (ApplyProjectEntity ap : aps) {
            setApplyProject(ap);
        }
        // 排序
        List<ApplyProjectEntity> result = new ArrayList<>();
        for (String apId : apIds) {
            ApplyProjectEntity ap = aps.stream().filter(t -> (t.getId().toString()).equals(apId)).findFirst().orElse(null);
            if (ap != null) {
                result.add(ap);
            }
        }
        return result;
    }
}